package org.jeecg.modules.tongxjl.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.leave.controller.AgLeaveController;
import org.jeecg.modules.leave.entity.AgLeave;
import org.jeecg.modules.leave.service.IAgLeaveService;
import org.jeecg.modules.shextdj.entity.DetaShextData;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.tongxjl.entity.AgTongxjl;
import org.jeecg.modules.tongxjl.entity.DetaKaoQRecord;
import org.jeecg.modules.tongxjl.service.IAgTongxjlService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by liudh on 2020/7/19.
 */
@Slf4j
public class SyncTongXjl implements Job {
    @Autowired
    private IAgTongxjlService agTongxjlService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IAgLeaveService agLeaveService;

    @Autowired
    AgLeaveController agLeaveController;



    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Timestamp sj = DateUtils.getTimestamp();
        log.info(String.format(" 同步通行记录，任务执行了，时间:" + sj));
        long t1 = System.currentTimeMillis();
        syncData();
        long t2 = System.currentTimeMillis();
        log.info(" 同步通行记录，任务执行结束了，执行时间:" + (t2-t1)+"开始时间："+sj);
    }

    boolean yetFinishSync = false;

    public Result<?> syncData() throws Exception {
        // 如果上次没同步完，直接返回
        if(yetFinishSync) {
            System.out.println("yet over");
            return null;
        }

        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("page", 1);
        map2.put("size", 5000);
        map.put("pagination", map2);

        map2 = new HashMap<>();
        map2.put("direction", "ASC");
        List list2 = new ArrayList();
        list2.add("sign_time");
        map2.put("fields", list2);
        map.put("sort", map2);

        map2 = new HashMap<>();
        Map map3 = new HashMap<String, Object>() {
            {
                put("field", "sign_time");
                put("ops", "gt");

                long shijc = DateUtils.str2Timestamp("2020-01-01 00:00:00").getTime();
                AgTongxjl agTongxjl = agTongxjlService.getOne(new QueryWrapper<AgTongxjl>().eq("shebcj","1").orderByDesc("tongxsj"), false);

                if(agTongxjl != null) {
                    System.out.println(DateUtils.formatTime(agTongxjl.getTongxsj()));
                    shijc = DateUtils.getTimestamp(agTongxjl.getTongxsj()).getTime();
                }
                put("value", shijc);
            }
        };

        List list = new ArrayList<>();
        list.add(map3);
        map2.put("and", list);
        map.put("filter", map2);
        map.put("t", DateUtils.getTimestamp());

        // System.out.println(JSONObject.toJSON(map).toString());
        log.info("商汤请求参数"+JSONObject.toJSON(map).toString());
        DetaShextData detaShextData = restTemplate.postForObject("http://26.29.23.93:8080/dw/strecords", map, DetaShextData.class);
        //   log.info("记录"+detaShextData.getRecords().get(0));

        LinkedList<AgTongxjl> zhul2 = new LinkedList <>();
        zhul2=(LinkedList<AgTongxjl>) redisUtil.get("主楼通行记录");
        LinkedList<AgTongxjl> dam2 = new LinkedList<>();
        dam2=(LinkedList<AgTongxjl>) redisUtil.get("大门通行记录");
        if (detaShextData != null) {
            List<AgTongxjl> batch = new ArrayList<>();


            if (redisUtil.get("主楼通行记录")==null){
                redisUtil.set("主楼通行记录",zhul2 );
            }
            if (redisUtil.get("大门通行记录")==null){
                redisUtil.set("大门通行记录", dam2);
            }


            //  System.out.println(detaShextData.getRecords().size());
            for (String str : detaShextData.getRecords()
            ) {
                DetaKaoQRecord detaKaoQRecord = JSON.parseObject(str, new TypeReference<DetaKaoQRecord>() {
                });
                if (detaShextData != null) {
                    AgTongxjl agTongxjl = new AgTongxjl();

                    agTongxjl.setShebcj("1");
                    // 商汤都是人脸核验
                    agTongxjl.setHeyfs("1");

//                    agTongxjl.setId(detaKaoQRecord.get_id());
                    agTongxjl.setXingm(detaKaoQRecord.getUser_name());
                    agTongxjl.setBum(detaKaoQRecord.getSsbm());

                    if(detaKaoQRecord.getDirection().equals("进"))
                        agTongxjl.setJincfx("1");
                    if(detaKaoQRecord.getDirection().equals("出"))
                        agTongxjl.setJincfx("2");

                    agTongxjl.setShibkh(detaKaoQRecord.getUser_ic_number());

                    agTongxjl.setShebmc(detaKaoQRecord.getDevice_name());
                    agTongxjl.setShenf(detaKaoQRecord.getUser_type());

                    long timestamp = Long.parseLong(detaKaoQRecord.getSign_time());
                    LocalDate localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDate();
                    LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
                    agTongxjl.setTongxsj(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
                    agTongxjl.setCreateTime(new Date());

                    agTongxjl.setZhuapzp(detaKaoQRecord.getCpicurl());
                    agTongxjl.setShibzp(detaKaoQRecord.getApicurl());

                    // 临时这么弄，后续商汤有个ic卡号就能做唯一标识了
                    agTongxjl.setRenybh(agTongxjl.getShibzp());

                    agTongxjl.setMobile(detaKaoQRecord.getMobile());

                    batch.add(agTongxjl);





                    //存入redis

                    if (agTongxjl.getShebmc().contains("主楼")){
                        zhul2.add(zhul2.size(),agTongxjl);
                        if (zhul2.size()>6){
                            zhul2.pop();
                        }






                        //  log.info("商汤-同步redis主楼通行记录"+agTongxjl.getTongxsj());

                    }
                    if (agTongxjl.getShebmc().contains("大门")&&agTongxjl.getShenf()!="3"){
                        dam2.add(dam2.size(),agTongxjl);
                        if (dam2.size()>6){
                            dam2.pop();
                        }

                          //  redisUtil.set("大门通行记录", dam2);

                        //   log.info("商汤-同步redis大门通行记录"+agTongxjl.getTongxsj());
                    }
                    if (agTongxjl.getShebmc().contains("中心校区1号门")&&agTongxjl.getShenf()!="3"){
                        dam2.add(dam2.size(),agTongxjl);
                        if (dam2.size()>6){
                            dam2.pop();
                        }




                        //   log.info("商汤-同步redis大门通行记录"+agTongxjl.getTongxsj());
                    }


                    //自动销假
                    AgLeave agLeave = agLeaveService.getOne(new QueryWrapper<AgLeave>().eq("processStatus",2).eq("applicant", agTongxjl.getXingm()));
                    if (agLeave!=null&&agTongxjl.getJincfx()=="1"&&agTongxjl.getShebmc().contains("大门")){
                        agLeaveController.xiaojia(agLeave.getId());
                    }

                }
            }
            redisUtil.set("主楼通行记录",zhul2);
            redisUtil.set("大门通行记录", dam2);

            try {
                yetFinishSync = true;
                agTongxjlService.saveBatch(batch, 5000);

            } catch (Exception error) {
                System.out.println(error.getMessage());
            } finally {
                yetFinishSync = false;
            }

            return Result.ok();
        }

        return Result.error("同步数据失败");
    }

}
